package com.zekdot.aptgateway.util;

import io.jsonwebtoken.*;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * Create by zekdot on 20-3-17.
 */
public class JwtUtil {
    public static String JWT_SECERT = "shudaixiong";
    public static String JWT_NOT_ADMIN = "{\"code\":1019,\"message\":\"您没有该权限\"}";
    public static String JWT_NOT_FORM = "{\"code\":1019,\"message\":\"您没有该权限\"}";
    public static String JWT_NO_INFO = "{\"code\":1020,\"message\":\"没有鉴权信息\"}";
    public static String JWT_FAIL = "{\"code\":1021,\"message\":\"无效的token\"}";
    public static String JWT_EXPIRE = "{\"code\":1022,\"message\":\"token过期，请重新登录\"}";
    public static String JWT_WRONG_IDENT = "{\"code\":1023,\"message\":\"token与身份不符\"}";

    /**
     * 生成密钥
     * @return
     */
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr) {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            checkResult.setErrCode(checkResult.JWT_ERRCODE_EXPIRE);
            checkResult.setSuccess(false);
        } catch (SignatureException e) {
            checkResult.setErrCode(checkResult.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        } catch (Exception e) {
            checkResult.setErrCode(checkResult.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        }
        return checkResult;
    }



    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    private static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
